package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
//@WebFilter("/*")//表示拦截的资源路径
public class LoginFilter implements Filter {
    ////路径匹配器，支持通配符  Spring中提供的路径匹配器 ;
    private static final AntPathMatcher apm=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //获取请求的路径
        String uri = request.getRequestURI();
        log.info("拦截到的资源为 {}",uri);
        //设置放行的资源路径
        String [] uris={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };
        //调用判断是否放行方法
        boolean flag = check(uris, uri);

        if (flag){
            log.info("放行资源不需要拦截 {}",uri);
            //放行资源
            filterChain. doFilter(request,response);
            return;
        }
        //判断用户是否登录
        Long emp = (Long) request.getSession().getAttribute("emp");
        if (emp!=null){
            log.info("用户已登录 {}",emp);
            //放行资源
            filterChain.doFilter(request,response);
            return;
        }
        //返回用户未登录信息
        log.info("用户未登录,响应前端");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 判断资源是否放行方法
     * @param uris
     * @param uri
     * @return
     */
    public boolean check(String[] uris,String uri){
        for (String s : uris) {
            //调用匹配器判断访问资源是否需要放行
            boolean flag = apm.match(s, uri);
            if (flag){
                return true;
            }
        }
        return false;
    }
}
